//
//  HYOAuthViewController.swift
//  WeiBo
//
//  Created by crazyfish on 16/3/12.
//  Copyright © 2016年 crazyfish. All rights reserved.
//

import UIKit
import SVProgressHUD

let WB_APPKEY = "1679064182"

let WB_REDIRRECT_URL = "http://www.itheima.com"

let WB_APPSECRET = "372a111c68bae0573cb5453f2e8a8dc9"

class HYOAuthViewController: UIViewController {

    private let OAuthLoginUrl = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REDIRRECT_URL)")!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        setupUI()
    }

    
    override func loadView() {
        
        view = webView
        

    }
   
    //设置视图
    private func setupUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
        
        navigationItem.title = "新浪微博"
        
    }

    //点击返回按钮的时间.让控制器消失
    @objc private func back(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //点击自动填充按钮的事件
    @objc private func autoFill(){
      
        let jsString = "document.getElementById('userId').value='18757414446';document.getElementById('passwd').value='zhanghengyu520'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
        
    }
    
    private lazy var webView: UIWebView = {
        
        let webView = UIWebView()
        
        webView.delegate = self
        //初始化一个
        //在闭包里面调用外部属性要使用self
        let request = NSURLRequest(URL: self.OAuthLoginUrl)
        
        webView.loadRequest(request)
        return webView
        
    }()
    
 
}


//当webview要加载某个请求的时候要访问这个方法是否要加载这个request

extension HYOAuthViewController: UIWebViewDelegate{
    
    //这个代理方法使用来在webView发送请求之前来询问这个方法是否访问返回值是true表示去访问,false表示不去访问
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //判断否为空
        guard let url = request.URL  else{
            
            return true
        }
        
        //判断是否是回调页面,如果是回调页面返回false不让用户看到回调页面信息
        
        let urlStr = url.absoluteString
        
        if urlStr.hasPrefix(WB_REDIRRECT_URL) {
            //截取code=后面的32位字符
            
            //query问号后面的字符串(参数)
        let query = url.query!
            
            //截取字符串获取code
        let code = query.substringFromIndex("code=" .endIndex)
            
       HYUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code, callback: { (isSuccess) -> () in
        
        if isSuccess{
            
            //跳转界面
            //当前控制器是moda出来.一定要在合适的位置dismiss不然会常驻内存
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                //1.获取appdelegate里面的window
                
                let delegate = UIApplication.sharedApplication().delegate! as! AppDelegate
                
                let window = delegate.window
                
                //2设置跟控制器
                
                window?.rootViewController = HYWelcomeViewController()

            })
            
            
        }else{
            
            SVProgressHUD.showErrorWithStatus("个人信息加载失败")
        }
        
        
       })

        return false
            
        }
        
        return true
    }
    
}
       


